package com.itcam.cm.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.itcam.cm.model.dto.user.UserLoginDto;
import com.itcam.cm.model.dto.user.UserRegisterDto;
import com.itcam.cm.model.entity.user.UserInfo;
import com.itcam.cm.user.mapper.UserInfoMapper;
import com.itcam.cm.user.service.UserInfoService;
import com.itcam.cm.user.utils.HttpUtils;
import com.itcam.cm.util.ItcamAssert
;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoServiceImpl implements UserInfoService {
    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    RedisTemplate<String,String> redisTemplate;


    @Override
    public void register(UserRegisterDto userRegisterDto) {

        String username = userRegisterDto.getUsername();
        String password = userRegisterDto.getPassword();
        String nickName = userRegisterDto.getNickName();
        String code = userRegisterDto.getCode();

        // 校验验证码
        String codeValueRedis = redisTemplate.opsForValue().get("phone:code:" + username);
        ItcamAssert
.isTrue(StringUtils.hasText(codeValueRedis)&&codeValueRedis.equals(code),"验证码错误");
        // 删除验证码
        redisTemplate.delete("phone:code:" + username);

        // 检查用户是否已经注册
        Integer integer = userInfoMapper.selectCountUserName(username);
        ItcamAssert
.isTrue(integer<=0,"用户名已注册");


        // 密码md5加密
        String passwordMd5 = DigestUtils.md5DigestAsHex(password.getBytes());
        

        // 注册成功
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(username);
        userInfo.setNickName(nickName);
        userInfo.setPassword(passwordMd5);
        userInfo.setPhone(username);
        userInfo.setAvatar("http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoj0hHXhgJNOTSOFsS4uZs8x1ConecaVOB8eIl115xmJZcT4oCicvia7wMEufibKtTLqiaJeanU2Lpg3w/132");
        userInfo.setStatus(1);
        userInfo.setSex(0);
        userInfoMapper.insertUser(userInfo);

    }

    @Override
    public void sendCode(String phone) {
        String validateCode = RandomStringUtils.randomNumeric(4);
        // 调用短信接口发送验证码
        sendAlisms(phone,validateCode);
        // 发送成功后，存入redis
        redisTemplate.opsForValue().set("phone:code:" + phone,validateCode,5, TimeUnit.MINUTES);
    }

    @Override
    public String login(UserLoginDto userLoginDto, String ip) {

        String username = userLoginDto.getUsername();
        String password = userLoginDto.getPassword();

        //校验参数
        ItcamAssert
.isTrue(username!=null&&password!=null,"用户名和密码不能为空");

        UserInfo userInfo = userInfoMapper.getByUsername(username);
        ItcamAssert
.notNull(userInfo,"用户不存在");

        //校验密码
        String md5InputPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        ItcamAssert
.isTrue(md5InputPassword.equals(userInfo.getPassword()),"密码错误");


        //更新登录信息
        userInfo.setLastLoginIp(ip);
        userInfo.setLastLoginTime(new Date());
        userInfoMapper.updateById(userInfo);

        String token = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForValue().set("user:login:" + token, JSON.toJSONString(userInfo), 30, TimeUnit.DAYS);
        return token;

    }

    @Override
    public UserInfo checkUserInfo(String token) {
        String userJson = redisTemplate.opsForValue().get("user:login:" + token);
        ItcamAssert
.notNull(userJson,"用户不存在");
        UserInfo userInfo = JSON.parseObject(userJson, UserInfo.class);
        return userInfo;
    }

    private void sendAlisms(String phone, String validateCode) {
        String host = "https://zwp.market.alicloudapi.com";
        String path = "/sms/sendv2";
        String method = "GET";
        String appcode = "6e125298cf0e49a3805302957b2fef4f";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", phone);
        querys.put("content", "【智能云】您的验证码是"+validateCode+"。如非本人操作，请忽略本短信");
        System.out.println("【智能云】您的验证码是"+validateCode+"。如非本人操作，请忽略本短信");

        try {
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            System.out.println(response.toString());
            //获取response的body
            System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
